import {Button, Image, ScrollView, Swiper, SwiperItem, Text, View} from '@tarojs/components'
import Taro, {useDidShow, useRouter} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useState} from 'react'
import {type Exhibition, getExhibition, getTicketTypes, type TicketType} from '@/api'

const ExhibitionDetail: React.FC = () => {
  const router = useRouter()
  const exhibitionId = Number(router.params.id)

  const [exhibition, setExhibition] = useState<Exhibition | null>(null)
  const [ticketTypes, setTicketTypes] = useState<TicketType[]>([])
  const [loading, setLoading] = useState(true)

  const loadData = useCallback(async () => {
    if (!exhibitionId) return

    setLoading(true)
    try {
      const [exhibitionResult, ticketTypesResult] = await Promise.all([
        getExhibition(exhibitionId),
        getTicketTypes(exhibitionId)
      ])

      if (exhibitionResult.success && exhibitionResult.data) {
        setExhibition(exhibitionResult.data)
      }

      if (ticketTypesResult.success && ticketTypesResult.data) {
        setTicketTypes(ticketTypesResult.data)
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [exhibitionId])

  useDidShow(() => {
    loadData()
  })

  const handleBooking = () => {
    Taro.navigateTo({
      url: `/pages/booking/index?exhibitionId=${exhibitionId}`
    })
  }

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }

  const parseJsonArray = (jsonStr?: string | string[]): string[] => {
    // 如果已经是数组，直接返回
    if (Array.isArray(jsonStr)) return jsonStr
    // 如果是字符串，尝试解析
    if (!jsonStr) return []
    try {
      return JSON.parse(jsonStr)
    } catch {
      return []
    }
  }

  if (loading) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gray-50">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  if (!exhibition) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gray-50">
        <Text className="text-gray-500">展览不存在</Text>
      </View>
    )
  }

  const highlights = parseJsonArray(exhibition.highlights)
  const notices = parseJsonArray(exhibition.notices)
  const images = parseJsonArray(exhibition.image_url)

  return (
    <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
      <ScrollView
        scrollY
        className="box-border"
        style={{height: '100vh', background: 'transparent', paddingBottom: '80px'}}>
        {/* 展览海报轮播图 */}
        {images.length > 0 && (
          <View className="relative">
            <Swiper
              className="w-full h-80"
              indicatorColor="rgba(255, 255, 255, 0.5)"
              indicatorActiveColor="#ffffff"
              circular
              indicatorDots
              autoplay>
              {images.map((image, index) => (
                <SwiperItem key={index}>
                  <Image src={image} mode="aspectFill" className="w-full h-80" />
                </SwiperItem>
              ))}
            </Swiper>
            {/* 图片数量指示器 */}
            <View className="absolute bottom-4 right-4 bg-black bg-opacity-50 px-3 py-1 rounded-full">
              <Text className="text-white text-xs">{images.length} 张海报</Text>
            </View>
          </View>
        )}

        <View className="px-4 py-6">
          <Text className="text-2xl font-bold text-gray-900 block mb-2">{exhibition.title}</Text>
          {exhibition.subtitle && <Text className="text-base text-gray-600 block mb-4">{exhibition.subtitle}</Text>}

          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <View className="flex items-start mb-3">
              <View className="i-mdi-map-marker text-blue-600 text-xl mr-3 mt-1"></View>
              <View className="flex-1">
                <Text className="text-sm text-gray-500 block mb-1">展览地点</Text>
                <Text className="text-base text-gray-900 block">{exhibition.location}</Text>
              </View>
            </View>

            <View className="flex items-start mb-3">
              <View className="i-mdi-calendar-range text-blue-600 text-xl mr-3 mt-1"></View>
              <View className="flex-1">
                <Text className="text-sm text-gray-500 block mb-1">展览时间</Text>
                <Text className="text-base text-gray-900 block">
                  {formatDate(exhibition.start_date)} - {formatDate(exhibition.end_date)}
                </Text>
              </View>
            </View>

            {exhibition.opening_hours && (
              <View className="flex items-start">
                <View className="i-mdi-clock-outline text-blue-600 text-xl mr-3 mt-1"></View>
                <View className="flex-1">
                  <Text className="text-sm text-gray-500 block mb-1">开放时间</Text>
                  <Text className="text-base text-gray-900 block">{exhibition.opening_hours}</Text>
                </View>
              </View>
            )}
          </View>

          {exhibition.description && (
            <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
              <Text className="text-lg font-bold text-gray-900 block mb-3">展览简介</Text>
              <Text className="text-sm text-gray-700 leading-relaxed block">{exhibition.description}</Text>
            </View>
          )}

          {highlights.length > 0 && (
            <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
              <Text className="text-lg font-bold text-gray-900 block mb-3">展览亮点</Text>
              <View className="space-y-2">
                {highlights.map((highlight, index) => (
                  <View key={index} className="flex items-start">
                    <View className="i-mdi-check-circle text-blue-600 mr-2 mt-1"></View>
                    <Text className="flex-1 text-sm text-gray-700">{highlight}</Text>
                  </View>
                ))}
              </View>
            </View>
          )}

          {ticketTypes.length > 0 && (
            <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
              <Text className="text-lg font-bold text-gray-900 block mb-3">票种价格</Text>
              <View className="space-y-3">
                {ticketTypes.map((ticket) => (
                  <View
                    key={ticket.id}
                    className="flex items-center justify-between py-3 border-b border-gray-100 last:border-b-0">
                    <View className="flex-1">
                      <Text className="text-base font-bold text-gray-900 block mb-1">{ticket.name}</Text>
                      {ticket.description && <Text className="text-xs text-gray-500 block">{ticket.description}</Text>}
                    </View>
                    <Text className="text-xl font-bold text-blue-600 ml-4">¥{Number(ticket.price).toFixed(2)}</Text>
                  </View>
                ))}
              </View>
            </View>
          )}

          {notices.length > 0 && (
            <View className="bg-amber-50 rounded-2xl p-4 mb-4">
              <View className="flex items-center mb-3">
                <View className="i-mdi-alert-circle text-amber-600 text-xl mr-2"></View>
                <Text className="text-base font-bold text-amber-900">注意事项</Text>
              </View>
              <View className="space-y-2">
                {notices.map((notice, index) => (
                  <View key={index} className="flex items-start">
                    <Text className="text-amber-600 mr-2">•</Text>
                    <Text className="flex-1 text-sm text-amber-900">{notice}</Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-3 safe-area-inset-bottom">
        <Button
          onClick={handleBooking}
          className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold text-base"
          style={{
            backgroundColor: '#2563eb',
            color: 'white',
            border: 'none'
          }}>
          立即购票
        </Button>
      </View>
    </View>
  )
}

export default ExhibitionDetail
